// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueResource from 'vue-resource'
import CurrUser from './components/global/CurrUser'
import VueSocketIO from 'vue-socket.io'
import clipboard from '../static/clipboard.js'
import App from './App.vue'
import CryptoJS from 'crypto-js'
import Captcha from 'tinydev-slider-captcha'
import 'tinydev-slider-captcha/tinydev-slider-captcha.css'

window.wgs84togcj02Location = false
// socket-io 连接配置
// console.log('window.ApiDoNameSocket',window.ApiDoNameSocket)
// Vue.use(new VueSocketIO({
//   debug: false,
//   connection: ApiDoNameSocket,
//   /* options: {
//     path: "/socket-client-server/"        // 默认路径: /socket-io/
//   } */
// }))

import 'vue-area-linkage/dist/index.css' // v2 or higher
import VueAreaLinkage from 'vue-area-linkage'
import MapTools from './components/tools/MapTools'
import AesUtils from './components/tools/AesUtils'
import SignUtil from './components/tools/SignUtil'

Vue.use(VueAreaLinkage)
Vue.use(Captcha)
// Vue.use(VueQr)

Vue.use(ElementUI, {
  size: 'mini',
})

Vue.prototype.AESKey = 'RrRWvsvWRcfQJiMR'

Vue.prototype.AESEnCode = function (msg) {
  var keyHex = CryptoJS.enc.Utf8.parse(Vue.prototype.AESKey)
  var option = {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7}
  var encrypted = CryptoJS.AES.encrypt(msg, keyHex, option)
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64)
}

Vue.prototype.AesDecode = function (msg) {
  let key = CryptoJS.enc.Utf8.parse(Vue.prototype.AESKey)
  // 返回的是一个Word Array Object，其实就是Java里的字节数组
  let decrypted = CryptoJS.AES.decrypt(msg, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

/**
 * 加密登录
 * @param form
 * @param callback
 * @param errorCallBack
 */
Vue.prototype.loginCrypto = function (form, callback, errorCallBack) {
  let $this = this
  var str = JSON.stringify(form)
  console.log('str', str)
  $this.MyRequest($this.ApiDoNameAuth + 'Public/r7wqyztzenb5k2k1', {
    data: $this.AESEnCode(JSON.stringify(form)),
    imageVerifyCode: form.imageVerifyCode
  }, function (data) {
    callback(data)
  }, function (res) {
    errorCallBack(res)
  })
}

// var str = Vue.prototype.AESEnCode('{"username":"15200000003","password":"a123456","imageVerifyCode":"7476"}')
// var str1 = Vue.prototype.AesDecode(str)
// console.log('加密内容: ' + str)
// console.log('解密内容: ' + str1)

// import 'swiper/dist/css/swiper.css'
// Vue.use(vueSwiper)

CurrUser.checkCache()
Vue.prototype.CurrUser = CurrUser
// console.log('Vue.prototype.CurrUser', Vue.prototype.CurrUser)
Vue.prototype.demoData = demoData
dict.VipLevelList = dict.VipLevelList.sort(function (a, b) {
  return a.level - b.level
})
Vue.prototype.dict = dict

Vue.config.productionTip = false
Vue.prototype.AppVersion = AppVersion

// 接口地址
Vue.prototype.ApiDoNameCommon = ApiDoNameCommon
Vue.prototype.ApiDoNameAuth = ApiDoNameAuth
Vue.prototype.ApiDoNameMember = ApiDoNameMember
Vue.prototype.UploadFileUrl = ApiDoNameCommon + 'File/upload'
Vue.prototype.UploadFileFroSearchImageUrl = ApiDoNameCommon + 'File/imageSearchUpload'
Vue.prototype.NoImageUrl = 'https://yangfan-shop.oss-cn-hangzhou.aliyuncs.com/image/no-image.jpg'
Vue.use(VueResource)
Vue.MyRequestLoading = {}

// 货币格式化方法
Vue.prototype.ToMoney = function (value) {
  return (value - 0).toFixed(2)
}

// 货币格式化方法
Vue.prototype.getIsShifu = function () {
  return localStorage.getItem('isShifu') && localStorage.getItem('isShifu') === '1'
}

/**

 * 获取屏幕宽高
 */
Vue.prototype.getWinSize = function () {
  if (localStorage.getItem('WinSize')) {
    return JSON.parse(localStorage.getItem('WinSize'))
  }
  var winSize = {
    width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  }
  if (winSize.width > 800) {
    winSize.width = 414
    winSize.height = 896
  }
  localStorage.setItem('WinSize', JSON.stringify(winSize))
  return winSize
}

Vue.prototype.getPositionAndCallBack = function (callback, alreadyTip) {
  let $this = this
  if (window.wgs84togcj02Location) {
    callback(window.wgs84togcj02Location)
  }
  if (typeof plus === 'undefined') {
    callback(this.CurrUser.getLocation())
    return
  }
  if (localStorage.getItem('AllowGetLocation') === '1' || alreadyTip) {
    plus.geolocation.getCurrentPosition(function (p) {
      var wgs84togcj02Location = MapTools.wgs84togcj02(p.coords.longitude, p.coords.latitude)
      window.wgs84togcj02Location = wgs84togcj02Location.join(',')
      callback(window.wgs84togcj02Location)
    }, function (e) {
      plus.nativeUI.toast('获取位置失败，请检查权限是否开启')
    })
    return
  }
  $this.$confirm('您是否同意获取您当前的位置信息?', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // alert('确取获取地址')
    localStorage.setItem('AllowGetLocation', '1')
    plus.geolocation.getCurrentPosition(function (p) {
      window.wgs84togcj02Location = wgs84togcj02Location.join(',')
      callback(window.wgs84togcj02Location)
    }, function (e) {
      plus.nativeUI.toast('获取位置失败，请检查权限是否开启')
    })
  }).catch(() => {
    localStorage.removeItem('AllowGetLocation')
    $this.setDefaultCity()
  })
}

/**

 * 获取屏幕宽高
 */
Vue.prototype.getSafeArea = function () {
  return {
    top: 0
  }
  // localStorage.removeItem('API_SAFE_AREA')
  // if (localStorage.getItem('API_SAFE_AREA')) {
  //   return JSON.parse(localStorage.getItem('API_SAFE_AREA'))
  // }
  // if (typeof api !== 'undefined' && api.safeArea && api.safeArea.top) {
  //   localStorage.setItem('API_SAFE_AREA', JSON.stringify(api.safeArea))
  //   return api.safeArea
  // } else {
  //   return {
  //     top: 44
  //   }
  // }
}

Vue.prototype.getFileName = function (filePath) {
  var splitArr = filePath.split('.')
  var fileName = splitArr[splitArr.length - 2] + '.' + splitArr[splitArr.length - 1]
  return fileName
}

// 应用头部信息
Vue.prototype.getHeader = function (url) {
  var platform = 'H5'
  if (typeof plus !== 'undefined') {
    platform = plus.os.name
  }
  const Deviceid = Vue.prototype.GetDeviceID()
  const signObj = SignUtil.generateSign(url, Deviceid)
  return {
    Authorization: 'Bearer ' + this.CurrUser.getToken(),
    Deviceid,
    Platform: platform,
    Usertype: 'Member',
    ...signObj
  }

}

Vue.prototype.handlerCity = function (str) {
  // 市级省
  if (str.indexOf('省') === -1) {
    var arr1 = str.split('市')
    if (arr1.length > 1) {
      var arr2 = arr1[1].split('县')
    }
  }
}

Vue.prototype.checkLoginAct = function (callback) {
  let $this = this
  if ($this.CurrUser.IsLogin()) {
    callback()
    return
  }
  $this.$confirm('当前操作需要进行登录,您是否前往登录?', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    $this.$router.push('/Login')
  }).catch(() => {
  })
}

Vue.prototype.toInt = function (n) {
  if (!n) {
    return 0
  }
  n -= 0
  n = Math.ceil(n)
  return n - 0
}

Vue.prototype.successTip = function (info, type, duration) {
  this.$message({
    offset: 70,
    center: true,
    message: info,
    type: type ? type : 'success',
    duration: duration ? duration : 1500,
  })
}

Vue.prototype.checkVerifyCode = function (rule, value, callback) {
  let mobileReg = /^\d{4,6}$/
  var result = value.match(mobileReg)
  if (result && result.input) {
    callback()
  } else {
    callback(new Error('验证码 格式错误!'))
  }
}

Vue.prototype.getScrollTop = function () {
  var scrollPos
  if (window.pageYOffset) {
    scrollPos = window.pageYOffset
  } else if (document.compatMode && document.compatMode != 'BackCompat') {
    scrollPos = document.documentElement.scrollTop
  } else if (document.body) {
    scrollPos = document.body.scrollTop
  }
  return scrollPos
}

Vue.prototype.getScrollHeight = function () {
  var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0
  if (document.body) {
    bodyScrollHeight = document.body.scrollHeight
  }
  if (document.documentElement) {
    documentScrollHeight = document.documentElement.scrollHeight
  }
  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight
  return scrollHeight
}

Vue.prototype.checkMobile = function (rule, value, callback) {
  var mobile = value + ''
  var regExp = /^1[3456789]\d{9}$/
  if (!regExp.test(mobile)) {
    return callback(new Error('手机号码 格式错误'))
  }
  return callback()
}

Vue.prototype.checkEmail = function (value) {
  var currStr = value + ''
  var regExp = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  return regExp.test(currStr)
}

Vue.prototype.checkExpressNumber = function (rule, value, callback) {
  var mobile = value + ''
  var regExp = /^[a-zA-Z0-9]{5,50}$/
  if (!regExp.test(mobile)) {
    return callback(new Error('快递单号 格式错误'))
  }
  return callback()
}

/**
 * 通用请求方法
 * @param url 域名后的接口地址
 * @param params  参数
 * @param callback  正确-回调
 * @param errorCallback  错误-回调
 * @constructor
 */
Vue.prototype.MyRequest = function (url, params, callback, errorCallback, header, isallData) {
  var $this = this
  if (Vue.MyRequestLoading[url] === true) {
    return
  }
  if (!(url.indexOf('http://') > -1 || url.indexOf('https://') > -1)) {
    url = this.ApiDoNameMember + url
  }

  if (typeof params === 'undefined' || params === null) {
    params = {}
  }
  params.city = this.CurrUser.City
  params.cityCode = this.CurrUser.getCityCode()
  if (url.indexOf('MemberAddress/') === -1) {
    params.location = this.CurrUser.getLocation()
  }

  // MemberAddress/create

  // alert('location: '+params.location)
  // if (typeof api!=='undefined'){
  //   api.toast({
  //     msg:'location: '+params.location
  //   })
  // }

  // 判断header参数
  var heaerParams
  if (typeof header === 'undefined' || header === null) {
    // 默认header参数
    heaerParams = this.getHeader(url)
  } else {
    heaerParams = header
  }
  Vue.MyRequestLoading[url] = true
  this.$http.post(url, params, {
    emulateJSON: true,
    credentials: true,
    headers: heaerParams
  }).then(function (response) {
    Vue.MyRequestLoading[url] = false
    var res = response.data
    Vue.MyRequestAllData = res

    if (res.code > 0) {
      // console.log('res', res)
      // 错误
      if (res.code === 1001 && (res.message === 'token 失效' || res.message === '2')) {
        if (CurrUser.getToken()) {
          $this.$message.error('登录状态异常')
        }
        CurrUser.AccessToken = ''
        CurrUser.IsLogin = false
        CurrUser.setCache(null)
        $this.$router.push('/Login')
        return
        // location.reload()
      } else {
        // 常规错误
        if (typeof errorCallback === 'function') {
          errorCallback(res)
        } else {
          // 常规参数错误
          // console.log('常规参数错误' + JSON.stringify(res))
          // $this.$message.error(res)
        }
      }
    } else {
      let tmpUrl = url.replace(window.ApiDoNameMember, '')
      // console.log('url',tmpUrl)
      if (tmpUrl === 'Member/info') {
        localStorage.setItem('MemberInfo', JSON.stringify(res.data))
      }
      // 正确回调
      if (typeof isallData !== 'undefined' && isallData === true) {
        callback(res)
      } else {
        callback(res.data)
      }
    }
  }, function (errorResponse) {
    Vue.MyRequestLoading[url] = false
    console.error('--------------------------http-请求错误--------------------------')
    console.log(JSON.stringify(errorResponse))
    // $this.$message.error(JSON.stringify(errorResponse))
  })
}

Vue.prototype.Upload = function (url, filePath, callback, errorCallback, header) {
  var $this = this
  if (Vue.MyRequestLoading[url] === true) {
    return
  }
  if (!(url.indexOf('http://') > -1 || url.indexOf('https://') > -1)) {
    url = this.ApiDoNameMember + url
  }

  if (typeof filePath === 'undefined' || filePath === null) {
    return alert('上传文件必须制定')
  }

  const formData = new FormData()
  formData.append('myUploadFile', filePath)
  // 判断header参数
  var heaerParams
  if (typeof header === 'undefined' || header === null) {
    // 默认header参数
    heaerParams = $this.getHeader()
  } else {
    heaerParams = header
  }
  // console.log('filePath',filePath)
  // console.log('header',heaerParams)
  heaerParams['Content-Type'] = 'multipart/form-data'
  Vue.MyRequestLoading[url] = true
  $this.$http.post(url, formData, {
    headers: heaerParams
  }).then(function (response) {
    Vue.MyRequestLoading[url] = false
    var res = response.data
    Vue.MyRequestAllData = res
    if (res.code > 0) {
      if (typeof errorCallback === 'function') {
        errorCallback(res)
      }
    } else {
      callback(res.data)
    }
  }, function (errorResponse) {
    Vue.MyRequestLoading[url] = false
    console.error('--------------------------http-请求错误--------------------------')
    console.log(JSON.stringify(errorResponse))
  })

  /*   console.log('文件路径',filePath)
    var reader = new FileReader();
    reader.onload = function(event) {
      // 上传文件内容
      var fileContent = event.target.result;
      console.log('读取到的文件',fileContent)
      const formData = new FormData()
      formData.append('myUploadFile', fileContent)
      // 判断header参数
      var heaerParams
      if (typeof header === 'undefined' || header === null) {
        // 默认header参数
        heaerParams = $this.getHeader()
      } else {
        heaerParams = header
      }
      Vue.MyRequestLoading[url] = true
      $this.$http.post(url, params, {
        headers: heaerParams
      }).then(function (response) {
        Vue.MyRequestLoading[url] = false
        var res = response.data
        Vue.MyRequestAllData = res

        if (res.code > 0) {
          if (typeof errorCallback === 'function') {
            errorCallback(res)
          }
        } else {
          callback(res.data)
        }
      }, function (errorResponse) {
        Vue.MyRequestLoading[url] = false
        console.error('--------------------------http-请求错误--------------------------')
        console.log(JSON.stringify(errorResponse))
      })
    } */

  // 根据文件路径读取文件
  reader.readAsText(filePath)
}

Vue.prototype.openNavigation = function (endLocation, addressName) {
  //方法1
  let longitude = endLocation[0]
  let latitude = endLocation[1]

  // 目的地名称
  let name = addressName
  let url = '' // app url
  let webUrl = '' // web url 用来为用户未安装导航软件时打开浏览器所使用url
  plus.nativeUI.actionSheet(
    {
      //选择菜单
      title: '选择地图应用',
      cancel: '取消',
      buttons: [
        {title: '高德地图'},
        {title: '百度地图'},
        // { title: "腾讯地图" },
      ], // 可选的地图类型
    },
    (e) => {
      // 判断用户选择的地图
      switch (e.index) {
        case 1:
          if (plus.os.name == 'Android') {
            url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
          } else {
            url = `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`
          }
          break
        case 2:
          url = `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=android.baidu.openAPIdemo`
          break
        case 3:
          url =
            `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=腾讯申请的key`
          break
        default:
          webUrl = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&src=mypage&coordinate=gaode`
          break
      }
      // 如果选中
      if (url != '') {
        url = encodeURI(url)
        // 打开 app 导航
        plus.runtime.openURL(url, (err) => {
          // 失败回到
          // 如果失败则说明未安装 直接 打开网页版进行导航
          // 毕竟用户可能没有安装app但一定安装的有浏览器
          plus.runtime.openURL(webUrl)
        })
      }
    }
  )
  //方法2
  // uni.openLocation({
  //   latitude: 31.975258,
  //   longitude: 118.769032,
  //   name: "想去的地方",
  //   success() {
  //     console.log("success");
  //   },
  // });
}

Vue.prototype.listToArray = function (list) {
  var arr = []
  list.forEach(function (name, index) {
    arr.push({
      id: index,
      name: name,
    })
  })
  return arr
}

Vue.prototype.mapToArray = function (map) {
  var arr = []
  Object.keys(map).forEach(function (key) {
    arr.push({
      id: key,
      name: map[key],
    })
  })
  return arr
}

Vue.prototype.pay = function (payType, data, successBack, errorBack) {
  let $this = this
  var channels = false
  var currPayChannel = false

  if (typeof plus === 'undefined') {
    return $this.$message.warning('当前客户端没集成该支付')
  }
  // 微信支付
  if (payType === 'wxpay') {
    plus.payment.getChannels(function (s) {
      channels = s
      for (var i in channels) {
        var channel = channels[i]
        if (channel.id === 'wxpay') {
          currPayChannel = channel
        }
      }
      // alert('params: '+JSON.stringify(payParams))
      plus.payment.request(currPayChannel, data, function () {
        // $this.$message.success('支付成功')
        if (typeof successBack === 'function') {
          successBack()
        }
        $this.$forceUpdate()
      }, function (res) {
        // $this.$message.info('未完成支付')
        if (typeof errorBack === 'function') {
          errorBack()
        }
      })
    }, function (e) {
      alert('获取支付通道列表失败：' + e.message)
    })
  }

  // 支付宝
  if (payType === 'alipay') {
    plus.payment.getChannels(function (s) {
      channels = s
      var nameArr = []
      for (var i in channels) {
        var channel = channels[i]
        if (channel.id === 'alipay') {
          currPayChannel = channel
        }
      }

      // alert('data: '+data)
      plus.payment.request(currPayChannel, data, function () {
        // $this.$message.success('支付成功')
        if (typeof successBack === 'function') {
          successBack()
        }
        $this.$forceUpdate()
      }, function (res) {

        // $this.$message.info('未完成支付')
        if (typeof errorBack === 'function') {
          errorBack()
        }
      })
    }, function (e) {
      alert('获取支付通道列表失败：' + e.message)
    })
  }
}

Vue.prototype.getAndUsePermission = function (permissionName, callback) {
  var resultList = api.hasPermission({
    list: [permissionName]
  })
  if (resultList[0].granted) {
    // 已授权，可以继续下一步操作
    callback()
  } else {
    api.confirm({
      msg: '应用需要您的授权才能进行操作',
      buttons: ['取消', '去设置']
    }, function (ret) {
      if (ret.buttonIndex == 2) {
        api.requestPermission({
          list: [permissionName],
        }, function (res) {
          if (res.list[0].granted) {
            // 已授权，可以继续下一步操作
            setTimeout(function () {
              callback()
            }, 1000)
          }
        })
      } else {
        api.toast({
          msg: '权限未开启'
        })
      }
    })
  }
}

/**
 * 获取随机字符串
 * @param len
 * @returns {string}
 * @constructor
 */
Vue.prototype.GetRandomStr = function (len) {
  if (!len) {
    len = 32
  }
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  var maxPos = $chars.length
  var str = ''
  for (var i = 0; i < len; i++) {
    str += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return str
}

/**
 * 获取设备ID
 * @param str
 * @return {number}
 * @constructor
 */
Vue.prototype.GetDeviceID = function () {
  var CurrDeviceID = localStorage.getItem('CurrDeviceID')
  if (!CurrDeviceID) {
    CurrDeviceID = AesUtils.Encrypt(Vue.prototype.GetRandomStr(32))
    localStorage.setItem('CurrDeviceID', CurrDeviceID)
  }
  return CurrDeviceID
}

Vue.prototype.GetFullStyle = function () {
  var winSize = this.getWinSize()
  return {
    width: winSize.width + 'px',
    height: winSize.height + 'px',
  }
}

Vue.prototype.getPlatform = function () {
  if (typeof (plus) !== 'undefined' && plus.device && plus.device.vendor === 'Apple') {
    return 'iOS'
  } else {
    return 'Android'
  }
}

/**
 * 进入页面
 */
Vue.prototype.addVisitLog = function (routePath) {
  let $this = this
  var shopId = 0
  var shopProductId = 0
  if (this.$route.name === 'ProductDetail') {
    shopProductId = this.$route.query.id
  }
  if (this.$route.name === 'ShopHome') {
    shopId = this.$route.query.id
  }
  var form = {
    page: routePath,
    pageParams: this.$route.query ? this.$route.query : '',
    platform: localStorage.getItem('platform') ? localStorage.getItem('platform') : 'Android',
    shopId: shopId,
    shopProductId: shopProductId,
  }
  var api = 'Public/addVisitLog'
  if ($this.CurrUser.IsLogin()) {
    api = 'Member/addVisitLog'
  }
  $this.MyRequest($this.ApiDoNameMember + api, form, function () {

  })
}

/**
 * 离开页面
 */
Vue.prototype.outVisitLog = function () {
  let $this = this
  var api = 'Public/outVisitLog'
  $this.MyRequest($this.ApiDoNameMember + api, {}, function () {

  })
}

Vue.prototype.copyClipBoard = function (text) {
  if (typeof plus !== 'object') {
    this.$message.error('只能在App中复制')
    return
  }
  clipboard.setText(text)
  plus.nativeUI.toast('复制成功')
}

Vue.prototype.checkAppVersion = function (callback) {
  let $this = this
  $this.MyRequest($this.ApiDoNameCommon + 'Public/checkAppVersion',
    {platform: Vue.prototype.getPlatform(), userClientType: 'Member'},
    function (response) {
      callback(response)
      $this.$forceUpdate()
    }, function (msg) {
      // $this.$message.error(msg)
    })
}

Vue.prototype.getCityByLocation = function (location, callback) {
  this.$http.get('https://restapi.amap.com/v3/geocode/regeo?output=json&location=' + location + '&key=973a6b7d29b3d57c9c4a0f92480c9c71&radius=1000&extensions=base', {}, {
    emulateJSON: true,
  }).then(function (response) {
    // console.log('response',response)
    callback(response.body.regeocode)
  }, function (errorResponse) {
    console.error('--------------------------http-请求错误--------------------------')
    console.log(JSON.stringify(errorResponse))
    // $this.$message.error(JSON.stringify(errorResponse))
  })
}

Vue.prototype.checkLoginUserStatus = function (route) {
  var needLoginPage = [
    // 'MemberHome', 'MemberSetup',
    'MemberCoupon', 'MemberLog', 'MemberPromotion', 'MemberInfo', 'MemberAddressList', 'MemberAddressForm', 'MyAMap',
    'MemberChangePassword', 'MemberChangeMobile', 'MemberWechatBinding', 'MemberBindingShopList', 'MemberShopCollectList', 'MemberProductCollectList',
    'ChatList', 'Chat', 'OrderList', 'OrderDetail', 'OrderExpress', 'OrderGroup', 'OrderReply', 'OrderApply', 'ConfirmOrder', 'PaySuccess',
    'ShopProductPurchaseList', 'ShopProductPurchaseDetail', 'EnterprisePayInfo', 'ConfirmPurchaseOrder'
  ]
  if (needLoginPage.indexOf(route.name) > -1) {
    if (!this.CurrUser.IsLogin()) {
      this.$router.push('/Login')
    }
  }
}

// 总线程

/* eslint-disable no-new */
window.currVueApp = null

function MyVueInit () {
  localStorage.setItem('platform', 'Android')
  if (Vue.prototype.getPlatform() === 'Apple') {
    localStorage.setItem('platform', 'iOS')
    if (localStorage.getItem('AppAgreement') !== '1') {
      location.replace('/static/privacy_dialog/index.html')
      return
    }
  }

  let bus = new Vue()
  Vue.prototype.bus = bus
  // 初始化Vue
  window.currVueApp = new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>',
    beforeCreate: function () {
      Vue.prototype.bus = this
      this.checkLoginUserStatus(this.$route)
    },
    watch: {
      $route: function (to, from) {
        var pageList = Object.keys(dict.RecordPageNameMap)
        let $this = this
        if (pageList.indexOf(to.name) > -1) {
          setTimeout(function () {
            $this.addVisitLog(to.name)
          }, 150)
        }
        if (pageList.indexOf(from.name) > -1) {
          setTimeout(function () {
            $this.outVisitLog(from.name)
          }, 150)
        }
        // console.log('pageList',pageList)
        $this.checkLoginUserStatus(to)
      }
    }
  })

}

window.isRun = false
document.addEventListener('plusready', function () {
  // console.log('plusready')
  // 2OXedNiCQKNIEJPc2lcYzV65R
  MyVueInit()
  window.isRun = true
})

// 旧版apicloud项目中转地址
window.apiready = function () {
  location.href = '/static/app.html'
}

setTimeout(function () {
  if (!window.isRun) {
    var currRoute = window.location.hash.split('?')[0].substring(2)
    if (window.location.hostname.indexOf('yangfankj.com') > -1) {
      if (['ProductDetail', 'Register'].indexOf(currRoute) > -1) {
        MyVueInit()
      } else {
        document.title = '未知'
      }
    } else {
      // document.title='未知'
      MyVueInit()
    }

  }
}, 2000)

window.showProductDetail = function (shopProductId, model) {
  // location.href='/#/ProductDetail?id='+shopProductId+'&model='+model
  // currVueApp.bus.$emit('ShowMessageProductCallBus',type,id)
  currVueApp.$router.push('ProductDetail?id=' + shopProductId + '&model=' + model)
}

window.currVideoPlayer = false

// App解析上传文件
Vue.prototype.uploadAndParseFile = function (filePath, callback, url) {
  if (typeof plus === 'undefined') {
    alert('只允许App上传文件')
  }
  if (!url) {
    url = this.UploadFileUrl
  }
  let $this = this
  var wt = plus.nativeUI.showWaiting()
  var task = plus.uploader.createUpload(url, {method: 'POST'}, function (returnData, status) {
      // console.log('returnData',returnData)
      var res = JSON.parse(returnData.responseText)
      // 上传完成
      if ((status - 0) == 200) {
        callback(res)
        wt.close()
      } else {
        plus.nativeUI.alert('上传失败:' + status)
        wt.close()
      }
    }
  )
  var DeviceID = $this.GetDeviceID()
  task.addFile(filePath, {key: 'myUploadFile', name: 'myUploadFile'})
  task.addData('DeviceID', DeviceID)
  if ($this.CurrUser.IsLogin()) {
    task.setRequestHeader('Authorization', 'Bearer ' + $this.CurrUser.getToken())
  }
  task.setRequestHeader('DeviceId', $this.GetDeviceID())
  task.setRequestHeader('UserType', 'Member')
  task.start()
}

window.playVideo = function (node) {
  var _src = node.getAttribute('_src')
  if (typeof plus !== 'undefined') {
    if (!window.currVideoPlayer) {
      window.currVideoPlayer = new plus.video.VideoPlayer('video', {
        src: _src
      })
    } else {
      window.currVideoPlayer.setOptions({src: _src})
    }
    window.currVideoPlayer.requestFullScreen()
    window.currVideoPlayer.play()
  } else {
    alert('暂时只支持app播放')
  }
  // alert(node)
}
